# -*- coding:utf-8 -*- 
# Author: json_steve

# -*- coding:utf-8 -*-

import datetime
from flask import request, current_app, jsonify, g
from iHome.utils.response_code import RET
from iHome.models import House, Order
from iHome.utils.common import login_required
from iHome import db,redis_store
from . import api


# 用户评价
@api.route('/orders/comment', methods=['PUT'])
@login_required
def order_comment():
    """
    1.获取参数
    ２．参数校验
    ３．写入数据库
    ４．返回
    :return:
    """
    user_id = g.user_id
    # 获取参数
    data_json = request.json
    order_id = data_json.get('order_id')
    comment = data_json.get('comment')
    # 校验参数
    if not all([order_id,comment]):
        return jsonify(errno=RET.PARAMERR,errmsg='参数错误')

    # 查询订单
    try:
        order = Order.query.filter(Order.id == order_id, Order.status == 'WAIT_COMMENT').first()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='查询数据错误')
    if not order:
        return jsonify(errno=RET.NODATA, errmsg='订单不存在')

    # 添加到数据库
    order.comment = comment
    order.status = 'COMPLETE'

    try:
        db.session.add(order)
        db.session.commit()
    except Exception as e:
        db.session.rollback()
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='存入数据库失败')
    # TODO 删除缓存
        # 删除房屋详情信息缓存
    try:
        redis_store.delete("house_detail_%d" % order.house_id)
    except Exception as e:
        current_app.logger.error(e)

    return jsonify(errno=RET.OK, errmsg='ok')


# 房东接受订单/拒绝订单
@api.route('/orders', methods=['PUT'])
@login_required
def change_order_status():
    """
    1.获取order_id
    ２.找到订单，待接订单
    ３．修改订单状态，
    ４．保存到数据库
    ５．返回值
    :return:
    """
    user_id = g.user_id

    data_json = request.get_json()

    # 取到订单号
    order_id = data_json.get('order_id')
    action = data_json.get('action')

    if not all([action, order_id]):
        return jsonify(errno=RET.PARAMERR, errmsg='参数错误')

    if action not in ('accept','reject'):
        return jsonify(errno=RET.PARAMERR,errmsg='参数错误')

    # 获取订单
    try:
        order = Order.query.filter(Order.id == order_id,Order.status == 'WAIT_ACCEPT').first()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='数据查询失败')
    if not order:
        return jsonify(errno=RET.NODATA, errmsg='未到订单')
    # 判断这个订单的房子的主人是不是登陆的用户
    if user_id != order.house.user_id:
        return jsonify(errno=RET.ROLEERR, errmsg='不允许操作')

    # 3 更改订单的状态
    if "accept" == action:
        # 接单
        order.status = "WAIT_COMMENT"
    elif "reject" == action:
        order.status = "REJECTED"
        # 取出原因
        reason = data_json.get("reason")
        if not reason:
            return jsonify(errno=RET.PARAMERR, errmsg="请填写拒单原因")
        # 保存拒单原因
        order.comment = reason
    try:
        db.session.commit()
    except Exception as e:
        db.session.rollback()
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='保存数据失败')
    return jsonify(errno=RET.OK, errmsg='OK')


# 展示订单页　客户租房／房东出租的房子
@api.route('/orders', methods=['GET'])
@login_required
def get_orders():
    """
    1.去用户的所有订单
    ２．返回

    :return:
    """
    user_id = g.user_id
    # 判断用户角色
    role = request.args.get('role')
    if not role:
        return jsonify(errno=RET.PARAMERR, errmsg='参数错误')
    if role not in ('custom', 'landlord'):
        return jsonify(errno=RET.PARAMERR, errmsg='参数错误')

    try:
        if role == 'custom':
            orders = Order.query.filter(Order.user_id == user_id).order_by(Order.create_time.desc()).all()
        if role == 'landlord':
            # 先查找房东下的所有房子
            houses = House.query.filter(House.user_id == user_id).all()
            # 取到所有房屋ｉｄ
            house_ids = [house.id for house in houses]
            # 在查找订单中房子在房东房子里的
            orders = Order.query.filter(Order.house_id.in_(house_ids)).order_by(Order.create_time.desc()).all()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='数据查询错误')

    order_list = []
    for order in orders:
        order_list.append(order.to_dict())
    return jsonify(errno=RET.OK, errmsg='ok', data={'orders': order_list})


# 提交订单
@api.route("/orders", methods=["POST"])
@login_required
def add_order():
    """
    1. 获取参数 > house_id, start_date_str, end_date_str
    2. 判断和校验参数
    3. 查询指定房屋id是否存在
    4. 判断当前时间段内该房屋是否有订单
    5. 生成订单模型，设置数据
    6. 数据保存
    7. 返回
    :return:
    """

    # 1. 获取参数
    user_id = g.user_id
    data_json = request.json
    house_id = data_json.get("house_id")
    start_date_str = data_json.get("start_date")
    end_date_str = data_json.get("end_date")

    # 2. 校验参数
    if not all([house_id, start_date_str, end_date_str]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    try:
        # 将日期字符串转成 datetime 对象
        start_date = datetime.datetime.strptime(start_date_str, "%Y-%m-%d")
        end_date = datetime.datetime.strptime(end_date_str, "%Y-%m-%d")
        # 判断开始时间与结束时间的大小
        assert start_date < end_date, Exception("结束时间必须大于开始时间")
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    # 3. 判断房屋是否存在
    try:
        house = House.query.get(house_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="查询数据错误")

    if not house:
        return jsonify(errno=RET.NODATA, errmsg="房屋不存在")
    # 判断是否是房主去预订
    if user_id == house.user_id:
        return jsonify(errno=RET.ROLEERR, errmsg="房东不能预订")

    # 4. 判断该房屋指定时间段内是否有冲突的订单
    try:
        filters = [Order.house_id == house_id, Order.begin_date < end_date, Order.end_date > start_date]
        # 取到冲突订单的数量
        order_count = Order.query.filter(*filters).count()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="查询数据错误")

    # 如果冲突订单的数量大于0，代表该房屋已被预订
    if order_count > 0:
        return jsonify(errno=RET.DATAERR, errmsg="房屋已被预订")

    # 5. 生成订单模型
    order = Order()
    # 设置属性值
    days = (end_date - start_date).days
    order.user_id = user_id
    order.house_id = house_id
    order.begin_date = start_date
    order.end_date = end_date
    order.days = days
    order.house_price = house.price
    order.amount = days * house.price

    # 将房屋的订单数量加1
    house.order_count += 1

    try:
        db.session.add(order)
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg="保存数据失败")

    return jsonify(errno=RET.OK, errmsg="ok")





